﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iwss.Document.Layouts.AjaxServices;
using Microsoft.SharePoint;
using System.Web;
using System.Collections;

namespace iwss.Document.Layouts.Services
{
    public class Receive : IAjaxService
    {
        public SPList ShareLib { get { return SPContext.Current.Web.Lists.TryGetList("共享库"); } }
        public SPList DocLib { get { return SPContext.Current.Web.Lists.TryGetList("文档库"); } }
        public string CurrentUserDocumentZoneAddress { get { return string.Format("{0}/{1}", DocLib.RootFolder.Url, Utilitys.GetUserName(SPContext.Current.Web.CurrentUser.Name)); } }

        public AjaxResult Excute(HttpContext context)
        {
            string ActionType = context.Request["act"].ToLower();
            AjaxResult result = null;

            switch (ActionType)
            {
                case "sharetome":
                    result = ReceiveSharetome(context);
                    break;
                case "receive":
                    result = ReceiveShareFolder(context);
                    break;
                case "setflag":
                    result = SetReceiveFlag(context);
                    break;
            }

            return result;
        }

        /// <summary>
        /// 获取共享给我的文档
        /// </summary>
        /// <returns></returns>
        private AjaxResult ReceiveSharetome(HttpContext context)
        {
            ArrayList res = new ArrayList();
            SPQuery query = new SPQuery()
            {
                Query = string.Format(@"<Where> 
                                             <Eq>
                                                <FieldRef Name='iwss_Sharer' LookupId='True'/>
                                                <Value Type='User'>{0}</Value>
                                             </Eq> 
                                       </Where>
                                       <OrderBy>
                                          <FieldRef Name='Modified' Ascending='False' />
                                       </OrderBy>", SPContext.Current.Web.CurrentUser.ID)
            };
            SPListItemCollection items = ShareLib.GetItems(query);

            res = GetShareFiles(items);

            return new AjaxResult(true, res);
        }

        private ArrayList GetShareFiles(SPListItemCollection items)
        {
            int itemCount = items.Count;
            ArrayList res = new ArrayList();
            for (int i = 0; i < itemCount; i++)
            {
                SPListItem item = items[i];
                res.Add(new
                {
                    Title = item["Title"],
                    ItemID = item.ID,
                    Url = item["iwss_Url"],
                    ModifyTime = item["Created"],
                    Sharer = Utilitys.GetUserName(item["Author"]),
                    FileItemID = item["iwss_LinkID"],
                    Icon = Utilitys.GetIcon(item["iwss_Url"].EToString()),
                    MyShare = false,
                    attr = new { target = "_blank" }
                });
            }
            return res;
        } 

        private AjaxResult SetReceiveFlag(HttpContext context)
        {
            List<string> recids = Utility.Asy(context.Request["ids"]);
            int id = -1;
            ShareLib.ParentWeb.AllowUnsafeUpdates = true;
            foreach (string item in recids)
            {
                if (item.IsNullOrEmpty()) continue;
                if (int.TryParse(item, out id))
                {
                    SPListItem listitem = ShareLib.GetItemById(id);
                    if (listitem == null) continue;

                    listitem["iwss_ShareType"] = "VIEWED";
                    listitem.Update();
                }
            }
            ShareLib.ParentWeb.AllowUnsafeUpdates = false;

            return new AjaxResult(true, "OK");
        }

        private AjaxResult ReceiveShareFolder(HttpContext context)
        {
            var res = new ArrayList();
            SPQuery query = new SPQuery()
            {
                Query = string.Format(@"<Where>
                                          <And>
                                             <Eq>
                                                <FieldRef Name='iwss_Sharer' LookupId='True' />
                                                <Value Type='User'>{0}</Value>
                                             </Eq>
                                             <Neq>
                                                <FieldRef Name='iwss_ShareType' />
                                                <Value Type='Text'>VIEWED</Value>
                                             </Neq>
                                          </And>
                                       </Where>
                                       <OrderBy>
                                          <FieldRef Name='Modified' Ascending='False' />
                                       </OrderBy>", SPContext.Current.Web.CurrentUser.ID)
            };
            SPListItemCollection items = ShareLib.GetItems(query);
            int itemCount = items.Count;

            for (int i = 0; i < itemCount; i++)
            {
                SPListItem item = items[i];
                res.Add(new
                {
                    Title = item["Title"],
                    ItemID = item.ID,
                    Url = item["iwss_Url"],
                    ModifyTime = item["Created"],
                    Icon = Utilitys.GetIcon(item["iwss_Url"].EToString()),
                    CheckBox = true,
                    attr = new { target = "_blank" }
                });
            }

            return new AjaxResult(true, res);
        }

    }
}
